import React, { useState } from "react";
import useSWR from "swr";
import { fetcher } from "../utils";
import { useNavigate } from "react-router-dom";

function ElectiveNew() {
    const navigate = useNavigate();
    const [selectedClass, setSelectedClass] = useState("");
    const [selectedStudents, setSelectedStudents] = useState([]);
    const [isBusy, setBusy] = useState(false);
    const [actionError, setActionError] = useState(null);

    // 拉取班次和学生数据
    const { data: classList } = useSWR("/api/class/list", fetcher);
    const { data: studentList } = useSWR("/api/student/list", fetcher);

    const handleStudentChange = (stu_sn) => {
        setSelectedStudents((prev) =>
            prev.includes(stu_sn)
                ? prev.filter((sn) => sn !== stu_sn)
                : [...prev, stu_sn]
        );
    };

    const handleSave = async () => {
        if (!selectedClass || selectedStudents.length === 0) {
            setActionError("请选择班次并至少选择一名学生");
            return;
        }
        setBusy(true);
        setActionError(null);
        try {
            let response = await fetch("/api/elective", {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify({ class_sn: parseInt(selectedClass), stu_sn_list: selectedStudents }),
            });
            if (!response.ok) {
                let errorText = await response.text();
                setActionError(errorText);
                return;
            }
            navigate("/elective/list");
        } finally {
            setBusy(false);
        }
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>新建选课</h3>
            </div>
            <div className="paper-body">
                <div className="field">
                    <label>班次：</label>
                    <select
                        value={selectedClass}
                        onChange={e => setSelectedClass(e.target.value)}
                    >
                        <option value="">请选择班次</option>
                        {Array.isArray(classList) && classList.map(cls => (
                            <option key={cls.sn} value={cls.sn}>{cls.name}</option>
                        ))}
                    </select>
                </div>
                <div className="field">
                    <label>选择学生：</label>
                    <div style={{ maxHeight: 200, overflowY: 'auto', border: '1px solid #eee', padding: 8 }}>
                        {studentList && studentList.map(stu => (
                            <div key={stu.stu_sn}>
                                <label>
                                    <input
                                        type="checkbox"
                                        value={stu.stu_sn}
                                        checked={selectedStudents.includes(stu.stu_sn)}
                                        onChange={() => handleStudentChange(stu.stu_sn)}
                                    />
                                    {stu.stu_name}（{stu.stu_no}）
                                </label>
                            </div>
                        ))}
                        {!studentList && <div>加载学生列表中...</div>}
                    </div>
                </div>
                {actionError && <div className="error">{actionError}</div>}
            </div>
            <div className="paper-footer">
                <button className="btn" onClick={handleSave} disabled={isBusy}>保存</button>
                <button className="btn" onClick={() => navigate("/elective/list")}>返回</button>
            </div>
        </div>
    );
}

export default ElectiveNew;